package com.common.app.utls

import android.app.DownloadManager
import android.content.Context
import android.os.Environment
import androidx.fragment.app.FragmentManager
import com.common.app.R
import com.common.app.data.bean.VersionResBean
import com.common.base.app.extras.dp2px
import com.common.base.app.extras.no
import com.common.base.app.extras.yes
import com.common.base.config.AppConfig
import com.common.base.utils.AppUtils
import com.common.base.utils.AppUtils.getString
import com.common.base.utils.DownloadServer
import com.common.base.utils.FileProvider7
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.ToastUtils.showToast
import java.io.File

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2022/8/29
 * <p>
 * 描述：APK下载类
 * <p>
 * 修订历史：
 */
class ApkDownLoadUtils(private val mContext: Context?, val version: VersionResBean?) {

    //下载器
    private var mDownloadServer: DownloadServer? = null

    //更新弹框
    private val downloadDialog = ApkDownloadDialog.newInstance(version)

    private val appName = getString(R.string.app_name) + version?.versionName?.replace(".","") +"-"+ TimeUtils.getDateToString(
        TimeUtils.getTimeDateLong(),
        "yyyyMMddHHmmss"
    ) + ".apk"

    init {
        appIsDownloadCheck().no { downloadAPK(version?.apkUrl) }
        downloadDialog.setOnUpdateClick { start() }
        downloadDialog.setOnInstallClick {
            mContext?.let {
                AppUtils.installApk(it, FileProvider7.getUriForFile(mContext, getFilePath()))
            }
        }

        //如果是强制升级，则保持需要升级的版本号，页面展示的时候判断是否是最新的版本号。防止偷渡
        SpUtilsManagement.removeFromKey(AppConfig.KEY_APK_DOWNLOAD_IS_COERCE)
        (version?.forced == 2).yes {
            version?.versionName?.let {
                SpUtilsManagement.putString(AppConfig.KEY_APK_DOWNLOAD_IS_COERCE, it)
            }
        }

    }

    private fun getFilePath(): File {
        val filePath = AppUtils.getContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
        val appPath = filePath?.path + "/" + appName
        return File(appPath)
    }

    private fun appIsDownloadCheck(): Boolean {
        val file = getFilePath()
        file.exists().yes { downloadDialog.isDownload = true }
        return file.exists()
    }

    //下载apk
    private fun downloadAPK(url: String?) {
        if (url == null) return
        mDownloadServer = null
        mDownloadServer = DownloadServer(mContext)
        mDownloadServer?.mName = appName
        mDownloadServer?.mTitle = getString(R.string.app_name_head) + "正在下载中"
        mDownloadServer?.mDescription = ""
        mDownloadServer?.mUrl = url
        //注册内容监听
        mDownloadServer?.registerContentObserver()
        //注册下载进度监听
        mDownloadServer?.mOnDownloadListener = object : DownloadServer.OnDownloadListener {
            override fun onDownload(currentSize: Long?, totalSize: Long?, status: Long?) {
                val index = totalSize?.let { currentSize?.div(it.toFloat()) }
                downloadDialog.setViewLayoutParams(dp2px(279), index ?: 0f)
                when (status?.toInt()) {
                    DownloadManager.STATUS_PAUSED -> {
                        //下载暂停
                    }

                    DownloadManager.STATUS_PENDING -> {
                        //等待开始
                    }

                    DownloadManager.STATUS_RUNNING -> {
                        //正在下载
                    }

                    DownloadManager.STATUS_SUCCESSFUL -> {
                        downloadDialog.installApp()
                        mDownloadServer?.unregisterContentObserver()
                        AppUtils.installApk(AppUtils.getApplication(), mDownloadServer?.mId)
                    }

                    DownloadManager.STATUS_FAILED -> {
                        //下载失败
                        downloadDialog.downloadFailed()
                    }

                    else -> {
                    }
                }
            }
        }
    }

    fun showDialog(manager: FragmentManager) {
        downloadDialog.isShowing().no {
            downloadDialog.show(manager)
        }
    }

    private fun start() {
        //开始下载
        if (mDownloadServer?.checkDownloadManagerEnable() != false) {
            mDownloadServer?.start()
        } else {
            showToast("请开启下载管理器")
        }
    }
}